package agentd_web

import (
	"context"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

var WebServerHost = "localhost"
var WebServerPort = 12720

type WebServer struct {
	httpServer *http.Server
}

func NewWebServer() *WebServer {
	return &WebServer{}
}

func (s *WebServer) Start() (errChan chan error) {
	errChan = make(chan error)
	go s.run(errChan)
	return
}

func (s *WebServer) run(errChan chan<- error) {
	// gin.Default 会自动使用 Logger 和 Recovery 中间件
	ginApp := gin.Default()

	corsConfig := cors.DefaultConfig()
	corsConfig.AllowAllOrigins = true
	// - AllowMethods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
	// - AllowHeaders: Origin, Content-Length, Content-Type
	// - AllowCredentials: false, credentials share disabled
	// - MaxAge: 12 * time.Hour, Preflight requests cached for 12 hours
	ginApp.Use(cors.New(corsConfig))

	ginApp.GET("/api/test/ping", handleTestPing)
	ginApp.GET("/api/test/echo", handleTestEcho)
	ginApp.GET("/api/test/sleep", handleTestSleep)

	ginApp.GET("/api/status/online", handleStatusOnline)

	ginApp.GET("/api/control/stop", handleControlStop)
	ginApp.GET("/api/control/restart", handleControlRestart)

	ginApp.GET("/api/wsclient/list", handleWsclientList)

	ginApp.GET("/api/system/type", handleSystemType)
	ginApp.GET("/api/system/user", handleSystemUser)
	ginApp.GET("/api/system/time/unix", handleSystemTimeUnix)

	ginApp.POST("/api/shell/exec_file", handleShellExecFile)
	ginApp.POST("/api/shell/exec_cmd", handleShellExecCmd)

	ginApp.GET("/api/ws/test/echo", handleWsTestEcho)
	ginApp.GET("/api/ws/shell/exec_file", handleWsShellExecFile)

	listenAddr := fmt.Sprintf("%s:%d", WebServerHost, WebServerPort)

	s.httpServer = &http.Server{
		Addr:    listenAddr,
		Handler: ginApp,
	}

	log.Printf("WebServer: listening on %s", listenAddr)
	err := s.httpServer.ListenAndServe()
	errChan <- err
}

func (s *WebServer) Stop() {
	s.httpServer.Shutdown(context.Background())
}
